package com.bill99.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

@Component
public class EmailUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);
	
	public Integer send(Map<String,String> param) {
		LOGGER.info("email send start。");
		
		Integer statusCode = null;
		
		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(param.get("sendEmailUrl"));
		
		String jsonMap = JsonUtil.convert2Json(param);
		String s = HexUtils.encode(jsonMap);
		
		post.addParameter(new NameValuePair("parameters",s));
		InputStream is = null;
		try {
			statusCode = client.executeMethod(post);
			is = post.getResponseBodyAsStream();
			String response = post.getResponseBodyAsString();
			System.out.println("statusCode="+statusCode);
			LOGGER.info("email send response: code={}, message={}", statusCode, response);
		} catch (Exception e) {
			LOGGER.info("send email error. ", e);
		} finally {
			try {
				if (is != null) is.close();
			} catch (IOException e) {
				is = null;
			}
			((SimpleHttpConnectionManager) client.getHttpConnectionManager()).shutdown();
			
			LOGGER.info("email send end。");
		}
		
		return statusCode;
	}


	public static void main(String[] args) {
		try {
			String source="https://cpro.baidustatic.com/cpro/ui/noexpire/ws/images/logo/logo_9f55db2.png";
			URL url = new URL(source);
			URLConnection uc = url.openConnection();
			InputStream in = uc.getInputStream();
			if (source.equalsIgnoreCase(uc.getURL().toString()))
				in.close();
			System.out.println("true");
		} catch (Exception e) {
			System.out.println("false");
		}
	}



}
